package com.lucian.ge.controller.shopadmin;

import com.lucian.ge.user.mapper.UserMapper;
import com.lucian.ge.util.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.lucian.ge.comman.model.ResultMap;
import com.lucian.ge.user.mapper.UserMapper;
import com.lucian.ge.user.model.User;

import javax.validation.Valid;
import java.util.Map;

/**
 * Created by Lucicol on 2019/6/19.
 */
@Api(value = "LoginController", description = "管理员登录接口")
@RestController
@RequestMapping("/manage/user")
public class UserManageController {
    private final UserMapper userMapper;
    private final ResultMap resultMap;

    @Autowired
    public UserManageController(UserMapper userMapper, ResultMap resultMap) {
        this.userMapper = userMapper;
        this.resultMap = resultMap;
    }

    @ApiOperation(value="管理员登录", notes="用户名/密码 {username,password}")
    @PostMapping("/login")
    @ResponseBody
    public ResultMap login(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) @Valid User user, BindingResult result) {
        //      参数校验
        if (result.hasErrors()) {

            return resultMap.fail().code(401).message(result.getFieldError().getDefaultMessage());
        }

        if (!user.getUsername().equals("17777777777")) {

            return resultMap.fail().code(401).message("管理员用户名错误");
        }

        String realPassword = userMapper.getPassword(user.getUsername());
        if (!realPassword.equals(user.getPassword())) {

            return resultMap.fail().code(401).message("密码错误");
        } else {

            Map<String, String> userInfo = userMapper.getUserInfo(user.getUsername());

            return resultMap.success().code(200).message("登录成功 2 秒后跳转到首页").token(JWTUtil.createToken(user.getUsername())).res(userInfo);
        }
    }
}
